import datetime
import json
import os
import traceback

from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import APIView

from pets import models
from pets.api.serializer import LogsSerializer
from tools.decorators import get_request_ip
from tools.pages import Mypage
from tools.tool import get_time_to_file_name, get_file_type


@method_decorator(get_request_ip, name='dispatch')
class UploadLogs(APIView):
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.query_params.dict()
            name = body.get('name')
            search_dict = {}
            if name:
                search_dict['name__icontains'] = name
            items = models.Logs.objects.filter(**search_dict).order_by('id')
            total = items.count()
            page = Mypage()
            page_list = page.paginate_queryset(items, request, view=self)
            ser = LogsSerializer(page_list, many=True)
            resp = {"code": 1, "data": ser.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)


def create_logs(data_dict):
    ser = LogsSerializer(data=data_dict)
    # print(ser.is_valid())
    if ser.is_valid():
        ser.save()

